/* eslint-disable react/no-unused-state */
import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import {Button, Card, Col, Divider, Dropdown, Form, Icon, Input, Menu, message, Modal, Row, Select, Tree, Popconfirm} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import styles from '../search.less';
import moment from 'moment';
import {ruleP,nameMaxLength,remarkMaxLength} from '@/utils/rule'
const {TextArea} = Input;
const FormItem = Form.Item;
const {TreeNode} = Tree;
const CreateForm = Form.create()(props => {
  const {modalVisible, form, addDataFn, updateFn, handleModalVisible,isDetail, text, adminData} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(text && text.id) {
        updateFn(fieldsValue,text)
      }else{
        addDataFn(fieldsValue);
      }
    });
  };
  if(isDetail) {
      const columns = [
        {
          title: '姓名',
          dataIndex: 'username',
        },
        {
          title: '登录名',
          dataIndex: 'username',
        },
        {
          title: '所属组织',
          dataIndex: 'organize',
        }
      ];
    return (
      <Modal
        destroyOnClose
        width={640}
        title="查看组织"
        visible={modalVisible}
        onCancel={() => handleModalVisible()}
        footer={[
            <Button key="back" type="primary" onClick={() => handleModalVisible()}>返回</Button>
          ]}
        className={styles.viewMore}
        >
        <Row>
          <Col md={24}>
            <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="组织名称">
              {text.orgName}
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="组织管理员">
              {text.orgAdminName}
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="组织描述">
              {text.remark}
            </FormItem>
          </Col>
        </Row>
      </Modal>
    )
  }else{
    const admin = adminData || [];
    return (
    <Modal
      destroyOnClose
      width={640}
      title={text?'编辑组织':'新增组织'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="组织名称">
        {form.getFieldDecorator('orgName', {
          rules: [{required: true, message: '组织名称不能为空'},
          {pattern:new RegExp(ruleP(4)[0],'g'), message:ruleP(4)[1]},
          {max:nameMaxLength()[0],message:nameMaxLength()[1]}],
          initialValue: text&&text.orgName || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="组织管理员">
        {form.getFieldDecorator('adminName', {initialValue: text&&text.orgAdminCode? text.orgAdminCode.split(','):[]
        })(<Select mode="multiple" placeholder="请选择" style={{width: '100%'}}>
          {
            admin&&admin.length&&admin.map((item,index) => {
              return (<Option key={item.userId} value={item.userCode}>{item.userName}</Option>)
            })
          }
        </Select>)}
      </FormItem>

      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="组织描述">
        {form.getFieldDecorator('remark', {rules:[{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}],initialValue: text&&text.remark || ''
        })(<TextArea
          style={{minHeight: 32}}
          placeholder=""
          rows={4}
        />)}
      </FormItem>
    </Modal>
  );
  }

});

@connect(({org, loading}) => ({
  org,
  loading: loading.models.org,
}))


@Form.create()
class OrgList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    isDetail: false,
    text: {},
    addParmas: {}, //新增时需要左边树的参数
  };

  columns = [
    {
      title: '组织名称',
      width: '20%',
      dataIndex: 'orgName',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '组织管理员',
      dataIndex: 'orgAdminName',
    },
    {
      title: '组织描述',
      width: '40%',
      dataIndex: 'remark',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>

          <a onClick={() => this.openDetailsPage(true,text)}>详情</a>
          <Divider type="vertical"/>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="edit" onClick={() => this.handleModalVisible(true,text)}>编辑</Menu.Item>
                <Menu.Item onClick={() => this.deleteData( record.id)}>删除</Menu.Item>
              </Menu>
            }
          >
            <a>更多 <Icon type="down"/></a>
          </Dropdown>
        </Fragment>
      ),
    },
  ];

  openDetailsPage = (flag,res) => {
    this.handleModalVisible(true,res);
    this.setState({
      isDetail: true
    });
  };

  deleteData = (id) => {
    if(id == 1 || (id.toString().indexOf(",") != -1)&&id.toString().split(",").indexOf("1") != -1) {
      Modal.warning({
        title: '不能删除根节点',
      });
      return
    }
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

   // 删除方法
  handleDeleteData(ids) {
    const { dispatch } = this.props;
    const { addParmas } = this.state;
    dispatch({
      type: 'org/remove',
      payload: {ids},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList({id:addParmas.id});
          this.treeData();// 组织树查询
          this.setState({
            selectedRows: [],
          })
        }else {
           Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
  }

    // 分页查询列表
  pageList(res,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const { selectedOrgId } = this.state;
    const values = {
      id: res && res.id || selectedOrgId,
      orgName: res && res.orgName || '',
      orgAdminName: res && res.adminName || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'org/getList',
      payload: values,
      callback: (obj) => {
        if(obj.result == "ok" && res.orgName) {
          this.treeData();// 组织树查询
        }
      },
    });
  }

  componentDidMount() {
    this.treeData();// 组织树查询
    this.pageList();//列表查询
    this.adminData();//组织管理员
  }

  // 组织树请求
  treeData() {
    const {dispatch} = this.props;
    const params = {
      pid: 0,
    }
    dispatch({
      type: 'org/getTree',
      payload: params,
    });
  }

  // 管理员
  adminData() {
    const {dispatch} = this.props;
    dispatch({
      type: 'org/admin',
    });
  }


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

 handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // form.resetFields();
      //点击查询
      this.setState({
        formValues: fieldsValue,
      })
      this.pageList(fieldsValue);
    });
  };

 // 新增弹框的显示和隐藏
  handleModalVisible = (flag,text) => {

    const {addParmas} = this.state;
    var parmas = JSON.stringify(addParmas);
    if(flag && parmas=="{}" && !text) {
      Modal.warning({
        title: '请先选择左边的组织',
      });
      return
    }
    this.setState({
      modalVisible: !!flag,
      isDetail: false,
      text: text
    });
  };

   // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const { addParmas } = this.state;
    const params = {
      id:text.id,
      orgName: fields.orgName,
      orgAdminCode:fields.adminName,
      parentId: text.id,
      remark:fields.remark,
    }
    dispatch({
      type: 'org/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList({id:addParmas.id});
          this.treeData();// 组织树查询
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    const { addParmas } = this.state;
    const params = {
      orgName: fields.orgName,
      orgAdminCode: fields.adminName,
      parentId: addParmas.id,
      remark:fields.remark,
    }
    dispatch({
      type: 'org/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList({id:addParmas.id});
          this.treeData();// 组织树查询
        }else {
           Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

// 渲染搜索框
  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="组织名称">
              {getFieldDecorator('orgName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="组织管理员">
              {getFieldDecorator('adminName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues, addParmas} = this.state;
    const assignObj = Object.assign(formValues,{id:addParmas.id});
    // 分页请求
    this.pageList(assignObj,pagination.pageSize,pagination.current-1);
  }

  /**
   * 选中树
   * @param id
   */
  onSelect = (e,info) => {
    const { form } = this.props;
    const props = info.node.props;
    const id = props.id;
    if(id == this.state.addParmas.id) {
      this.setState({
        addParmas: {},
        selectedOrgId:"",
      });
      return
    }
    this.pageList({id})
    this.setState({
      selectedOrgId:id,
      addParmas: {
        id:props.id,
        orgAdminCode:props.orgAdminCode,
        parentId: props.parentId,
        parentIds:props.parentIds,
      },
      formValues: {},
    });
    form.resetFields();
  };

  render() {
    const {
      org: {treeList, data, adminData},
      loading,
    } = this.props;
    const {selectedRows, modalVisible,isDetail, text} = this.state;

    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      isDetail: isDetail,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn
    };

    const loop = data => data&&data.length&&data.map((item) => {
      if (item.children) {
        return (
          <TreeNode key={item.id} title={item.orgName} {...item}>
            {loop(item.children||[])}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.orgName} {...item}/>;
    });

    return (
      <PageHeaderWrapper title="组织管理">
        <GridContent className={styles.userCenter}>
          <Row gutter={24}>
            <Col lg={6} md={24}>
              <Card bordered={false} style={{marginBottom: 24}}>
                <div className={styles.treeScroll}>
                {treeList&&treeList.length?<Tree
                  showLine={true}
                  defaultExpandedKeys={['1']}
                  onSelect={this.onSelect}
                >

                  {loop(treeList||[])}

                </Tree>:null}
                </div>
              </Card>
            </Col>
            <Col lg={18} md={24}>
              <Card bordered={false}>
                <div className={styles.tableList}>
                  <div className={styles.tableListForm}>{this.renderForm()}</div>
                  <div className={styles.tableListOperator}>
                    <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                      新增
                    </Button>
                    {/*selectedRows.length > 0 && (
                      <span>
                        <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                      </span>
                    )*/}
                  </div>
                  <TableList
                    className={styles.tdPadding}
                    selectedRows={selectedRows}
                    loading={loading}
                    data={data}
                    columns={this.columns}
                    onSelectRow={this.handleSelectRows}
                    onChange={this.handleStandardTableChange.bind(this)}
                    rowKey={record => record.id}
                  />
                </div>
              </Card>
            </Col>
          </Row>
        </GridContent>

        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text} adminData={adminData} />
      </PageHeaderWrapper>
    );
  }
}

export default OrgList;
